<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
               :disabled="method==='view'"
               label-width="120px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="名称" prop="name"
                          :rules="[
                 ]">
              <el-input v-model="inputForm.name" placeholder="请填写名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceTypeId"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.deviceTypeId" placeholder="请选择设备类型" style="width: 100%;"
                         @change="(val) => loadDeviceList(val)">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保周期" prop="cycleType"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.cycleType" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('maintenance_cycle_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.deviceId" multiple placeholder="请选择设备" style="width: 100%;">
                <el-option
                  v-for="item in deviceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周期值" prop="cycleValue"
                          :rules="[
                 ]">
              <el-input v-model="inputForm.cycleValue" placeholder="如每3个月一次时=3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate"
                          :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate"
                          :rules="[
                 ]">
              <el-date-picker
                v-model="inputForm.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%;"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否开启" prop="enabled"
                          :rules="[
                 ]">
              <el-select v-model="inputForm.enabled" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('maintenance_plan_enabled')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description"
                          :rules="[
                 ]">
              <el-input type="textarea" :rows="3" v-model="inputForm.description" placeholder="请填写描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      title: '',
      method: '',
      visible: false,
      loading: false,
      categoryList: [], // 设备类型列表
      deviceList: [], // 设备列表
      inputForm: {
        id: '',
        planNo: '',
        name: '',
        description: '',
        deviceId: [],
        deviceTypeId: '',
        cycleType: '',
        cycleValue: '',
        startDate: '',
        endDate: '',
        enabled: ''
      }
    }
  },
  components: {},
  methods: {
    // 恢复表单数据
    recover (form, source) {
      if (source && typeof source === 'object') {
        Object.keys(form).forEach(key => {
          if (source[key] !== undefined) {
            if (typeof form[key] === 'object' && form[key] !== null) {
              form[key] = this.recover(form[key], source[key])
            } else {
              form[key] = source[key]
            }
          }
        })
      }
      return form
    },
    init (method, id) {
      this.method = method
      this.inputForm.id = id
      if (method === 'add') {
        this.title = `新建维保计划`
        // 设置开始日期默认为当天
        this.inputForm.startDate = this.formatDate(new Date())
        // 设置状态默认为开启
        this.inputForm.enabled = '启用'
      } else if (method === 'edit') {
        this.title = '修改维保计划'
      } else if (method === 'view') {
        this.title = '查看维保计划'
      }
      this.visible = true
      this.loading = false

      // 加载设备类型列表
      this.loadCategoryList()

      this.$nextTick(() => {
        this.$refs.inputForm.resetFields()
        if (method === 'edit' || method === 'view') { // 修改或者查看
          this.loading = true
          this.$http({
            url: `/workorder/maintenacePlan/queryById?id=${this.inputForm.id}`,
            method: 'get'
          }).then(({data}) => {
            this.inputForm = this.recover(this.inputForm, data.maintenacePlan)
            // 如果有设备类型ID，加载对应的设备列表
            if (this.inputForm.deviceTypeId) {
              this.loadDeviceList(this.inputForm.deviceTypeId).then(() => {
                // 确保设备列表加载完成后再反显多选设备
                if (this.inputForm.deviceId) {
                  this.inputForm.deviceId = typeof this.inputForm.deviceId === 'string'
                    ? this.inputForm.deviceId.split(',').filter(Boolean)
                    : Array.isArray(this.inputForm.deviceId)
                      ? this.inputForm.deviceId
                      : []
                } else {
                  this.inputForm.deviceId = []
                }
                this.loading = false
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.loading = false
            }
          })
        }
      })
    },
    // 表单提交
    doSubmit () {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          // 创建提交数据副本，将设备ID数组转换为字符串
          const submitData = {
            ...this.inputForm,
            deviceId: Array.isArray(this.inputForm.deviceId)
              ? this.inputForm.deviceId.filter(Boolean).join(',')
              : typeof this.inputForm.deviceId === 'string'
                ? this.inputForm.deviceId
                : ''
          }
          this.loading = true
          this.$http({
            url: `/workorder/maintenacePlan/${this.inputForm.id ? 'update' : 'save'}`,
            method: 'post',
            data: submitData
          }).then(({data}) => {
            if (data && data.success) {
              this.visible = false
              this.$message.success(data.msg)
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        }
      })
    },

    // 加载设备类型列表
    loadCategoryList () {
      this.$http({
        url: '/device/equipmentCategory/list',
        method: 'get'
      }).then(({data}) => {
        if (data && data.success) {
          // 根据实际响应结构调整数据处理逻辑
          const list = data.page && data.page.list ? data.page.list : []
          this.categoryList = list.map(item => {
            return {
              id: item.id || '',
              name: item.name || ''
            }
          })
        } else {
          this.$message.error(data.msg || '加载设备类型失败')
        }
      }).catch(error => {
        console.error('加载设备类型出错:', error)
        this.$message.error('加载设备类型失败，请检查网络连接')
      })
    },

    // 根据设备类型ID加载设备列表
    // 格式化日期为 yyyy-MM-dd
    formatDate (date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    loadDeviceList (categoryId) {
      return new Promise((resolve) => {
        if (!categoryId) {
          this.deviceList = []
          this.inputForm.deviceId = []
          resolve()
          return
        }

        this.$http({
          url: '/device/equipment/list',
          method: 'get',
          params: {
            categoryId: categoryId
          }
        }).then(({data}) => {
          if (data && data.success) {
            const list = data.page && data.page.list ? data.page.list : []
            this.deviceList = list.map(item => {
              return {
                id: item.id || '',
                name: item.name || ''
              }
            })
            // 过滤掉不在新设备列表中的已选项（多选）
            if (Array.isArray(this.inputForm.deviceId)) {
              const allowedIds = new Set(this.deviceList.map(i => i.id))
              this.inputForm.deviceId = this.inputForm.deviceId.filter(id => allowedIds.has(id))
            }
          } else {
            this.$message.error(data.msg || '加载设备列表失败')
            this.deviceList = []
          }
          resolve()
        }).catch(error => {
          console.error('加载设备列表出错:', error)
          this.$message.error('加载设备列表失败，请检查网络连接')
          this.deviceList = []
          resolve()
        })
      })
    }
  }
}
</script>
